const app = getApp();

Page({
  data: {
    banners: [],
    categories: [],
    recommendProducts: [],
    searchValue: '',
    loading: true
  },

  onLoad() {
    this.loadBanners();
    this.loadCategories();
    this.loadRecommendProducts();
  },

  async loadBanners() {
    try {
      const res = await app.request({
        url: '/product/banners/',
        method: 'GET'
      });

      this.setData({
        banners: res.data || []
      });
    } catch (error) {
      console.error('获取轮播图失败', error);
      this.setData({ banners: [] });
    }
  },

  async loadCategories() {
    try {
      const res = await app.request({
        url: '/product/categories/',
        method: 'GET'
      });

      // 确保返回的数据是数组
      const categories = Array.isArray(res.results) ? res.results : (Array.isArray(res) ? res : []);
      
      // 添加默认图标
      const categoriesWithIcon = categories.map(item => ({
        ...item,
        icon: item.icon || '/assets/images/default-category.png'
      }));

      this.setData({
        categories: categoriesWithIcon
      });
    } catch (error) {
      console.error('获取分类列表失败', error);
      this.setData({ categories: [] });
    }
  },

  async loadRecommendProducts() {
    try {
      const res = await app.request({
        url: '/product/products/recommend/',
        method: 'GET'
      });

      this.setData({
        recommendProducts: res.data || [],
        loading: false
      });
    } catch (error) {
      console.error('获取推荐商品失败', error);
      this.setData({ 
        recommendProducts: [],
        loading: false 
      });
    }
  },

  handleSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    });
  },

  handleSearch() {
    const { searchValue } = this.data;
    if (!searchValue.trim()) {
      return;
    }
    wx.navigateTo({
      url: `/pages/search/search?keyword=${searchValue}`
    });
  },

  handleCategoryTap(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/category/category?id=${id}`
    });
  },

  handleProductTap(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${id}`
    });
  }
}); 